package ua.org.nuos.sdms.clientgui.server.services;

import ua.org.nuos.sdms.clientgui.server.exceptions.AuthenticationException;
import ua.org.nuos.sdms.middle.entity.enums.Role;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 06.11.11
 * Time: 17:22
 * To change this template use File | Settings | File Templates.
 */
public class LoginService implements Serializable {

    private static final Logger logger = Logger.getLogger(LoginService.class.getName());
    private static String[] ALLOWED_ROLES = {Role.client};

    private ServiceLocator serviceLocator;

    public LoginService(ServiceLocator serviceLocator) {
        this.serviceLocator = serviceLocator;
    }

    public void login(HttpServletRequest request, String user, String password) throws ServletException, AuthenticationException {
        if (request.getRemoteUser() != null) {
            request.logout();
        }
        try {
            request.login(user, password);
            long id = serviceLocator.getAuthenticationBean().getCurrentUser().getId();
            boolean isRegistrationComplete = serviceLocator.getRegistrationBean().isUserRegistrationComplete(id);
            if (!isRegistrationComplete) {
                throw new AuthenticationException(user);
            }
            boolean isUserRoleAllowed = false;
            for (String role : ALLOWED_ROLES) {
                if (request.isUserInRole(role)) {
                    isUserRoleAllowed = true;
                    break;
                }
            }
            if (!isUserRoleAllowed) {
                throw new AuthenticationException(user);
            }
        } catch (ServletException ex) {
            logger.log(Level.SEVERE, "Request login failure.", ex);
            throw new AuthenticationException(user);
        }
    }

    public void logout(HttpServletRequest request) throws ServletException {
        if (request.getRemoteUser() != null) {
            request.logout();
//            request.getSession().invalidate();
        }
    }
}
